<template>
  <div>
    <!------------------------头部宠物列表------------------------------->
    <div style="display: flex; flex-wrap: wrap; gap: 10px;margin: 10px;" class="coverImg">
      <img class="pet_cover_imgs"
           v-for="(item, index) in petList"
           :key="index"
           :src="item.coverImg"
           @click="handleSelectPet(item)"/>
    </div>
    <!------------------------宠物信息------------------------------->
    <div class="healthInfo_contain">
      <div class="healthInfo_title">
        <div style="flex: 1 1 50%">
          <div style="display: flex;">
            <img :src=" selectedPet.coverImg "
                 style="height: 68px;width: 68px;object-fit: cover;border-radius: 40px;">
            <div style="padding-left: 3%;width: 84%;">
              <div style="font-weight: bold">{{ selectedPet.petName }}</div>
              <div class="pet_info_name" style="font-weight: normal;font-size: 12px;margin-top: 8px;color: #797979">
                品种:{{ selectedPet.specis }} 年龄:{{ selectedPet.age }}
                体重:{{ selectedPet.weight }}kg
              </div>
              <div class="pet_info_tag"
                   style="font-weight: normal;font-size: 12px;margin-top: 8px;color: #797979">健康评分：
                <StarFilled
                    v-for="(star, index) in Math.floor((selectedPet.vaccinationReconds ||0 + selectedPet.dewormingRecords || 0)/3+1)"
                    :key="index"
                    style="color: #ffe223;"
                />
                <StarOutlined style="color: #ffe223 "/>
              </div>
            </div>
            <div style="font-size: 14px">
              <MehFilled style="color: #4CAF50"/>
              健康状况良好
            </div>
          </div>
        </div>
      </div>

      <div class="healthInfo_statistics">
        <div style="display: flex">
          <div style="width: 80%;font-weight: bold;font-size: 20px">健康数据统计</div>
          <div style="display: flex;flex: 1 1 30%">
            <div @click="getPetHealth(7)" class="statistic_button">近7天</div>
            <div @click="getPetHealth(30)" class="statistic_button">近30天</div>
            <input placeholder="自定义" :placeholder="自定义" v-model="queryData.dateRange"
                   @keyup.enter="getPetHealth(queryData.dateRange)" class="statistic_input statistic_button"/>
          </div>
        </div>
        <div>
          <!--          折线图放置-->
          <div ref="lineChartRef" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      <div class="healthInfo_record">
        <div style="flex: 1">
          <div style="font-size: large;font-weight: bold">活动记录</div>
          <div style="padding-left: 200px;padding-bottom: 10px;padding-top: 10px;">
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <YuqueFilled/>
                晨间散步
              </div>
              <div style="flex: 1">{{ selectedPetActivity?.walk || 0 }}分钟</div>
            </div>
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <GitlabFilled/>
                玩耍时间
              </div>
              <div style="flex: 1">{{ selectedPetActivity?.play || 0 }}分钟</div>
            </div>
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <HighlightFilled/>
                训练时间
              </div>
              <div style="flex: 1">{{ selectedPetActivity?.train || 0 }}分钟</div>
            </div>

          </div>
          <!-- 添加按钮 -->
          <el-button type="primary" @click="handleAddActivity" style="margin-top: 100px; margin-left: 250px">添加活动记录</el-button>
          <el-button type="danger" @click="clearActivityForm" style="margin-top: 100px; margin-left: 10px">清空</el-button>
        </div>
        <div style="flex: 1">
          <div ref="barchartRef" style="width: 100%; height: 300px;"></div>
          <!-- 添加按钮 -->
          <el-button type="primary" @click="handleAddPetDrink" style="margin-top: 10px; margin-left: 300px">添加饮水记录</el-button>


        </div>

      </div>
      <!-- 添加饮水记录对话框 -->
      <el-dialog v-model="showAddDrinkDialog" title="添加饮水记录" width="30%">
        <el-form :model="drinkForm" label-width="100px">
          <el-form-item label="宠物ID">
            <el-input v-model="drinkForm.petId" disabled></el-input>
          </el-form-item>
          <el-form-item label="饮水量 (ml)">
            <el-input-number v-model="drinkForm.water" :min="0" placeholder="请输入饮水量"></el-input-number>
          </el-form-item>
          <el-form-item label="记录时间">
            <el-date-picker v-model="drinkForm.createTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="showAddDrinkDialog = false">取消</el-button>
      <el-button type="primary" @click="addPetDrink">提交</el-button>
    </span>
        </template>
      </el-dialog>
      <!-- 添加活动记录对话框 -->
      <el-dialog v-model="showAddActivityDialog" title="添加活动记录" width="30%">
        <el-form :model="activityForm" label-width="100px">
          <el-form-item label="宠物ID">
            <el-input v-model="activityForm.petId" disabled></el-input>
          </el-form-item>
          <el-form-item label="晨间散步 (分钟)">
            <el-input-number v-model="activityForm.walk" :min="0" placeholder="请输入晨间散步时间"></el-input-number>
          </el-form-item>
          <el-form-item label="玩耍时间 (分钟)">
            <el-input-number v-model="activityForm.play" :min="0" placeholder="请输入玩耍时间"></el-input-number>
          </el-form-item>
          <el-form-item label="训练时间 (分钟)">
            <el-input-number v-model="activityForm.train" :min="0" placeholder="请输入训练时间"></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAddActivityDialog = false">取消</el-button>
            <el-button type="primary" @click="addPetActivity">提交</el-button>
          </span>
        </template>
      </el-dialog>
      <div class="healthInfo_remind">
        <div></div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getHealthCheckUpRecords,
  getPetActivityListAPI,
  getPetDrinkInfoAPI,
  getPetListAPI,
  addPetDrink, addPetActivityAPI, cleanPetActivityAPI
} from "@/api/petApi";
import {parseTime2, parseTime3} from "@/utils/timeUtil";
import {MehFilled, StarFilled, StarOutlined, YuqueFilled, GitlabFilled, HighlightFilled} from '@ant-design/icons-vue';
import * as echarts from 'echarts';


export default {
  name: "HealthInfo",
  components: {
    StarOutlined, StarFilled, YuqueFilled, MehFilled, GitlabFilled, HighlightFilled // 注册图标组件
  },
  data() {
    return {
      selectedPetId: undefined,
      selectedPet: {},
      showAddDrinkDialog: false,
      showAddActivityDialog: false, // 新增活动记录弹出框显示标志
      activityForm: { // 新增活动记录表单数据
        petId: undefined,
        walk: 0,
        play: 0,
        train: 0,
      },
      //柱状图配置信息
      barOption: {
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} kg'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '饮水量 (ml)'
        },
        series: [
          {
            name: '日期',
            type: 'bar',
            data: []
          }
        ]
      },
      selected: 0,
      queryData: {
        petId: 1,
        dateRange: ''
      },
      drinkForm: {},
      petList: [],
      lineOption: {
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '体重',
            type: 'line',
            data: [],
            smooth: true, // 平滑曲线
          },
        ],
      },
      petActivityList: [],
      selectedPetActivity: {},
      petActivityListMap: new Map(),
      petDrinkList: [],
      petDrink: {},
      petDrinkMap: new Map(),
      lineChart: null,
      barChart: null,
    }
  },
  // watch: {
  //   petList(newPetList) {
  //     // 当 petList 数据加载完成后，并且还没有选中宠物时，默认选中第一个
  //     if (newPetList && newPetList.length > 0 && !this.selectedPetId) {
  //       this.handleSelectPet(newPetList[0]);
  //     }
  //   }
  // },
  methods: {
    //清空活动时间
    clearActivityForm() {
      cleanPetActivityAPI(this.selectedPetId).then(() => {
        this.$message.success("清空成功")
        this.getPetActivityList()
      })
    },
    handleAddPetDrink() {
      this.drinkForm = {
        petId: this.selectedPetId,
        water: 0,
        createTime: new Date()
      }
      this.showAddDrinkDialog = true
    },
    handleAddActivity() {
      this.activityForm = {
        petId: this.selectedPetId,
        walk: 0,
        play: 0,
        train: 0,
      }
      this.showAddActivityDialog = true
    },
    getPetHealth(dateRange = 120) {
      this.queryData.petId = this.selectedPetId
      this.queryData.dateRange = dateRange
      this.lineOption.series[0].data = [];
      this.lineOption.xAxis.data = [];
      getHealthCheckUpRecords(this.queryData).then(res => {
        // 确保返回的数据是有效的
        if (res && res.data && Array.isArray(res.data)) {
          // 确保 series 和 xAxis 的数据结构已初始化
          this.lineOption.series = this.lineOption.series || [{data: []}];
          this.lineOption.xAxis = this.lineOption.xAxis || [{data: []}];

          // 从数组末尾开始向前遍历
          for (let i = 0; i < res.data.length - 1; i++) {
            const item = res.data[i];
            item.createdAt = parseTime3(item.createdAt); // 解析时间

            // 将数据推入对应的数组
            this.lineOption.series[0].data.push(item.weight);
            this.lineOption.xAxis.data.push(item.createdAt);
          }
        }
        this.lineChart.setOption(this.lineOption);
      });
    },
    getPetActivityList() {
      getPetActivityListAPI().then(res => {
        console.log("获取数据")
        this.petActivityList = res.data
        this.petActivityList.forEach(item => {
          // 将petActivityList放到Map中
          this.petActivityListMap.set(item.petId, item)
        })

      //  更新页面数据
        this.selectedPetActivity = this.petActivityListMap.get(this.selectedPetId) || {}
      })
    },
    // 获取所有宠物的饮水信息
    getPetDrinkList() {
      getPetDrinkInfoAPI().then(res => {
        let petDrinkList = res.data
        if (!Array.isArray(petDrinkList)) {
          return
        }

        this.petDrinkList = petDrinkList
        this.petDrinkList.forEach(item => {
          item.createTime = parseTime3(item.createTime)

          // 将宠物饮水信息添加到 Map 中，方便柱状图获取
          if (this.petDrinkMap.has(item.petId)) {
            let existingItem = this.petDrinkMap.get(item.petId);
            existingItem.water.push(item.water)
            existingItem.createTime.push(item.createTime)
          } else {
            this.petDrinkMap.set(item.petId, {
              id: item.petId,
              water: [item.water],
              createTime: [item.createTime]
            });
          }
        })
      })
    },

    // 切换宠物时触发
    handleSelectPet(item) {
      console.log("选择")

      this.selectedPetId = item.petId
      // 1. 更新宠物数据（缓存）
      this.petList.forEach(item => {
        if (item.petId === this.selectedPetId) {
          this.selectedPet = item
        }
      })

      // 2. 更新健康记录统计（折线图）（请求）
      this.getPetHealth()

      // 3. 更新记录（缓存）
      this.selectedPetActivity = this.petActivityListMap.get(this.selectedPetId) || {}
      // 4. 更新宠物饮水量（柱状图）（缓存）
      // 冲缓存中获取数据
      let selectedPetDrink = this.petDrinkMap.get(this.selectedPetId);
      // 4.2 更新 柱状图 的options数据
      if (selectedPetDrink) {
        this.barOption.xAxis.data = selectedPetDrink.createTime
        this.barOption.series[0].data = selectedPetDrink.water
      }
      // 4.3 重新渲染柱状图
      this.barChart.setOption(this.barOption);
    },

    addPetDrink() {
      // 验证表单数据
      if (!this.drinkForm.water || !this.drinkForm.createTime) {
        this.$message.error('请填写完整的饮水记录信息');
        return;
      } // 提交表单数据到后端
      addPetDrink(this.drinkForm).then(res => {
        if (res.code === 200) {
          this.$message.success('饮水记录添加成功');
          this.showAddDrinkDialog = false;
          this.getPetDrinkList(); // 刷新饮水记录
        } else {
          this.$message.error('饮水记录添加失败');
        }
      }).catch(err => {
        this.$message.error('饮水记录添加失败');
        console.error(err);
      });
    },
    addPetActivity() {
      // 验证表单数据
      if (!this.activityForm.walk && !this.activityForm.play && !this.activityForm.train) {
        this.$message.error('请填写完整的记录信息');
        return;
      }
      // 提交表单数据到后端
       addPetActivityAPI(this.activityForm).then(async res => {
        if (res.code === 200) {
          this.$message.success('活动记录添加成功');
          this.showAddActivityDialog = false;
          let a = await this.getPetActivityList(); // 刷新活动记录
          // 3. 更新活动记录（缓存）
          setTimeout(() => {
            // 更新数据
            console.log("更新数据")
            this.selectedPetActivity = this.petActivityListMap.get(this.selectedPetId) || {}
          })
        } else {
          this.$message.error('活动记录添加失败');
        }
      }).catch(err => {
        this.$message.error('活动记录添加失败');
        console.error(err);
      });
    },
    getPetList: function () {
      getPetListAPI().then(res => {
        let petList = res.data
        if (!Array.isArray(petList)) {
          console.log('获取宠物列表失败')
          return
        }

        this.petList = petList.map(item => {
          const updatedItem = {...item};
          updatedItem.personalityTrait = updatedItem.personalityTraits.split(';');
          if (updatedItem.imgs && updatedItem.imgs.includes(';')) {
            updatedItem.phtos = updatedItem.imgs.split(';');
          }
          updatedItem.dateOfBirth = parseTime2(updatedItem.dateOfBirth);
          return updatedItem;
        });
        // 获取完宠物数据后默认选中第一个宠物
        this.handleSelectPet(this.petList[0])
      });
    },
    init() {
      // 初始化图表
      this.lineChart = echarts.init(this.$refs.lineChartRef);
      this.barChart = echarts.init(this.$refs.barchartRef);

      // !!!需要确保先获取宠物活动记录和宠物饮水信息
      // 获取宠物活动记录
      this.getPetActivityList();
      //获取宠物饮水信息
      this.getPetDrinkList();

      // 获取宠物列表
      this.getPetList()
    }
  },

  mounted() {
    this.init()
  }
}
</script>
<style>
.healthInfo_contain {
  margin-left: 7%;
  margin-right: 7%;
  background: rgba(211, 211, 211, 0.27);
}

.healthInfo_title {
  display: flex;
}

.healthInfo_statistics {
  margin-top: 2%;
}

.healthInfo_record {

  display: flex;
  flex: 1 1 50%;

}

.healthInfo_remind {

}

.pet_cover_imgs {
  object-fit: cover;
  height: 45px;
  width: 45px;
  border-radius: 20px;
  border: #a7b1bb solid 2px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: transform 90ms ease;
}

.pet_cover_imgs:hover {
  cursor: pointer;
  transform: scale(1.1);
  transition: height 300ms ease, transform 300ms ease; /* 过渡动画 */

}

.pet_cover_imgs:hover {
  transform: translateY(0);
}

.pet_cover_imgs:not(:hover) {
  transform: translateY(-25px);
}

.coverImg {
  overflow: hidden; /* 隐藏超出部分 */
}

.statistic_input {
  width: 80px;
  border: none !important; /* 移除所有边框 */
}

.statistic_input::placeholder {
  color: #000000;
  font-weight: normal;
  font-size: 16px;
}

.statistic_input:focus::placeholder {
  opacity: 0; /* 隐藏 placeholder */
  color: transparent; /* 可选：确保 placeholder 完全透明 */
}

.statistic_button {
  cursor: pointer;
  margin-right: 10px;
  background: rgba(176, 176, 176, 0.18);
  padding: 5px;
  width: 80px;
  text-align: center;
}

</style>